package com.yn.iotxiao.controller.Device;


import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.HikHttpUtil;
import com.yn.iotxiao.Utils.HttpHelper;
import com.yn.iotxiao.Utils.JsonHelper;
import com.yn.iotxiao.Utils.StringUtil;
import com.yn.iotxiao.request.PageRequest;
import com.yn.iotxiao.response.ErrorResult;
import com.yn.iotxiao.response.ResponseResult;
import com.yn.iotxiao.sql.entity.Device.DeviceInfo;
import com.yn.iotxiao.sql.services.Device.DeviceInfoService;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


@RequestMapping("/device")
@Slf4j
@RestController
@ResponseResult
public class DeviceController {

    @Autowired
    DeviceInfoService service;
    @PutMapping
    public Object putDevice(HttpServletRequest servletRequest, @Validated @RequestBody DeviceInfo request) {

        JSONObject jsonObject = HttpHelper.get("http://" + request.getIp() + "/ISAPI/System/deviceInfo",
                request.getLoginId(),request.getPassword());

        log.info("deviceInfo:" + jsonObject.toString());
        if (jsonObject == null) {
            return new ErrorResult("设备认证失败");
        }
        if (jsonObject.containsKey("serialNumber") && !StringUtils.isBlank(jsonObject.get("serialNumber").toString())) {
           String serialNumber = jsonObject.getString("serialNumber");
           if (request.getType() == 1) {
               request.setSerialnumber(serialNumber.substring(serialNumber.length() - 9,serialNumber.length()));
           }else if (request.getType() == 2) {
               request.setSerialnumber(serialNumber.substring(serialNumber.length() - 13,serialNumber.length() - 4));
           }

        }else {
            return new ErrorResult("设备信息获取失败");
        }

        request.setModel(jsonObject.getString("model"));

        if (StringUtils.isBlank(request.getDeviceid())) {
            request.setDeviceid(StringUtil.getUUID());
        }

        request.setLastTime(new Date());
        request.setModel(JsonHelper.getWithKey(jsonObject,"model").toString());

        int result = service.insert(request);
        if (result > 0) {
            if(request.getType() == 1) {

                //门禁加创建事件
                HikHttpUtil httpUtil = new HikHttpUtil(request.getIp(), "/ISAPI/Event/notification/httpHosts/1",
                        request.getLoginId(), request.getPassword(),true);
                String inboundData="<HttpHostNotification>"
                        + "<id>" + 1 + "</id>"
                        + "<url>/api/event</url>"
                        + "<protocolType>HTTP</protocolType>"
                        + "<parameterFormatType>json</parameterFormatType>"
                        + "<addressingFormatType>ipaddress</addressingFormatType>"
                        + "<ipAddress>" + servletRequest.getServerName() + "</ipAddress>"
                        + "<portNo>" + servletRequest.getServerPort() + "</portNo>"
                        + "<httpAuthenticationMethod>none</httpAuthenticationMethod>"
                        + "</HttpHostNotification>";
                log.info("xml:" + inboundData);
                try {
                    var response = httpUtil.doPut(inboundData);
                    log.info("事件上报返回:" + response.toString());

                } catch (Exception e) {
                    log.info("事件上报失败:" +e);
                    throw new RuntimeException(e);
                }
            }
            return "保存成功";
        }
        return  new ErrorResult("保存失败");
    }

    @PostMapping("list")
    public Object getList(@RequestBody PageRequest request) {
        var list = service.getList(request.getSearchKey(), request.getPage(), request.getPageSize());
        var total = service.getTotal(request.getSearchKey());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("total",total);
        return  jsonObject;
    }

    @DeleteMapping("/{deviceid}")
    public Object deleteWithSerId(@PathVariable String deviceid) {
        int result = service.delete(deviceid);
        if (result > 0) {
            return "删除成功";
        }

        return  new ErrorResult("删除失败");
    }

    @GetMapping("/notice/{deviceid}")
    public String noticeDevice(HttpServletRequest request, @PathVariable String deviceid) {

        var device = service.getWithKey(deviceid);
        if (device == null || StringUtils.isBlank(device.getDeviceid())) {
            throw new RuntimeException("设备不存在");
        }

        //创建事件
        HikHttpUtil httpUtil = new HikHttpUtil(device.getIp(), "/ISAPI/Event/notification/httpHosts/1",
                device.getLoginId(), device.getPassword(),true);
        String inboundData="<HttpHostNotification>"
                + "<id>" + 1 + "</id>"
                + "<url>/api/event</url>"
                + "<protocolType>HTTP</protocolType>"
                + "<parameterFormatType>json</parameterFormatType>"
                + "<addressingFormatType>ipaddress</addressingFormatType>"
                + "<ipAddress>" + request.getServerName() + "</ipAddress>"
                + "<portNo>" + request.getServerPort() + "</portNo>"
                + "<httpAuthenticationMethod>none</httpAuthenticationMethod>"
                + "</HttpHostNotification>";
        log.info("xml:" + inboundData);
        try {
            var response = httpUtil.doPut(inboundData);
            log.info("事件上报返回:" + response.toString());

        } catch (Exception e) {
            log.info("事件上报失败:" +e);
            throw new RuntimeException(e);
        }
        return "设置成功";
    }
}
